import time
from concurrent.futures import ThreadPoolExecutor, as_completed

import requests
import tornado.ioloop
import tornado.web
import json
import datetime

"""
    个股详情整体介绍：
        目标：在通达信中点击个股时，能够显示出个股的相关信息
        步骤：
            1.初始化时，需要传入代码和名称
            2.

"""
def concurrent_http_requests(urls,max_workers=20):
    """
    并发发送HTTP请求并返回结果。

    :param urls: 要发送请求的URL列表。
    :param max_workers: 线程池中的最大线程数，默认为5。
    :return: 一个包含(url, response_data)元组的列表，其中response_data是响应的JSON数据或错误信息。
    """
    def fetch_url(url):
        try:
            response = requests.get(url)
            response.raise_for_status()  # 检查响应状态码是否为200
            return url, response.json()  # 返回URL和响应的JSON数据
        except requests.RequestException as e:
            return url, {'error': str(e)}  # 返回URL和错误信息

    results = []
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_url = {executor.submit(fetch_url, url): url for url in urls}
        for future in as_completed(future_to_url):
            url = future_to_url[future]
            try:
                result = future.result()
                results.append(result)
            except Exception as e:
                results.append((url, {'error': str(e)}))

    return results

# 初始化
class DataHandler(tornado.web.RequestHandler):
    def get(self,param):
        print(param)

        # 渲染模板并传递 JSON 数据
        self.render("ggxq.html",
                    stock_code=param.split('&')[0],
                    stock_name=param.split('&')[1])


"""
    总共需要传递的参数：
    股票代码：gpdm
"""
class WwriteSource1Handler(tornado.web.RequestHandler):
    def get(self, gpdm, sc, dms):
        xmlHttp11_url11 = "https://apphwhq.longhuvip.com/w1/api/index.php?a=GetKLineZhangTing&apiv=w38&c=StockLineData&PhoneOSNew=1&UserID=1904246&DeviceID=037520ec-5c84-34a1-8d7a-813a91437308&VerSion=5.17.0.0&Token=20947f154edaba1afb79c6ee7e2e3b78&StockID="+gpdm+"&"
        xmlHttp12_url12 = "https://apphis.longhuvip.com/w1/api/index.php?a=GetDayZhangTing&st=25&c=HisLimitResumption&PhoneOSNew=1&DeviceID=037520ec-5c84-34a1-8d7a-813a91437308&VerSion=5.13.0.0&Token=0&Index=0&apiv=w35&StockID="+gpdm+"&UserID=0&"
        xmlHttp14_url14 = "https://apparticle.longhuvip.com/w1/api/index.php?a=GetConceptJXBKw23&apiv=w24&c=StockF10Basic&StockID=" + gpdm
        xmlHttp15_url15 = "https://apphq.longhuvip.com/w1/api/index.php?a=GetStockIDPlate&apiv=w32&Type=2&c=StockL2Data&StockID=" + gpdm
        xmlHttp16_url16 = "https://flash-api.xuangubao.cn/api/stock_spotlight?symbol=" + dms

        urls = [xmlHttp11_url11,xmlHttp12_url12,xmlHttp14_url14,xmlHttp15_url15,xmlHttp16_url16]
        responses = concurrent_http_requests(urls)
        datas = {}
        for url, data in responses:
            if url == xmlHttp11_url11:
                datas['xmlHttp11'] = data
            if url == xmlHttp12_url12:
                datas['xmlHttp12'] = data
            if url == xmlHttp14_url14:
                datas['xmlHttp14'] = data
            if url == xmlHttp15_url15:
                datas['xmlHttp15'] = data
            if url == xmlHttp16_url16:
                datas['xmlHttp16'] = data

        # 将数据转换为 JSON 并作为响应返回
        self.write(json.dumps(datas))
        self.set_header("Content-Type", "application/json")

class WwriteSource2Handler(tornado.web.RequestHandler):
    def get(self, gpdm, sc, dms):
        xmlHttp21_url21 = "https://apphq.longhuvip.com/w1/api/index.php?a=GetFeaturedSection&c=StockL2Data&apiv=w26&StockID=" + gpdm + "&"
        xmlHttp22_url22 = "https://apparticle.longhuvip.com/w1/api/index.php?a=GetConceptJXBKw23&apiv=w24&c=StockF10Basic&StockID=" + gpdm

        urls = [xmlHttp21_url21,xmlHttp22_url22]
        responses = concurrent_http_requests(urls)
        datas = {}
        for url, data in responses:
            if url == xmlHttp21_url21:
                datas['xmlHttp21'] = data
            if url == xmlHttp22_url22:
                datas['xmlHttp22'] = data

        # 将数据转换为 JSON 并作为响应返回
        self.write(json.dumps(datas))
        self.set_header("Content-Type", "application/json")

class SubclassHandler(tornado.web.RequestHandler):
    def get(self, bkdm):
        xmlHttp3_url3 = "https://apphq.longhuvip.com/w1/api/index.php?a=SonPlate_Info&c=ZhiShuRanking&PhoneOSNew=1&VerSion=5&apiv=w26&PlateID=" + bkdm
        urls = [xmlHttp3_url3]
        responses = concurrent_http_requests(urls)
        datas = {}
        for url, data in responses:
            if url == xmlHttp3_url3:
                datas['xmlHttp3_url3'] = data


        # 将数据转换为 JSON 并作为响应返回
        self.write(json.dumps(datas))
        self.set_header("Content-Type", "application/json")

class UpdateHandler(tornado.web.RequestHandler):
    def get(self, bdm, rq, k9, fenshi1, fenshi2, typeSort):

        url1_1025 = "https://apphq.longhuvip.com/w1/api/index.php?a=GetPlate_Info_QJ&apiv=w33&c=ZhiShuRanking&PhoneOSNew=1&PlateID=" + bdm + "&Date=&"
        url2_1025 = "https://apphis.longhuvip.com/w1/api/index.php?a=GetPlate_Info_QJ&apiv=w33&c=ZhiShuRanking&PhoneOSNew=1&PlateID=" + bdm + "&Date=" + rq + "&"
        if k9 == "1":
            url_1025 = url2_1025
        else:
            url_1025 = url1_1025

        url1 = "https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=30&c=ZhiShuRanking&PhoneOSNew=1&old=1&DeviceID=037520ec-5c84-34a1-8d7a-813a91437308&VerSion=5.13.0.0&IsZZ=0&Index=0&apiv=w35&Type=6&IsKZZType=0&PlateID=" + bdm + "&"
        url2 = "https://apphis.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=30&c=ZhiShuRanking&PhoneOSNew=1&old=1&DeviceID=00000000-20e2-de83-0000-000075d2bc63&VerSion=5.10.0.2&IsZZ=0&Token=eae05af9b2237485e90e8165e55b0f20&Index=0&Date=" + rq + "&apiv=w33&Type=6&IsKZZType=0&UserID=1904945&PlateID=" + bdm + "&"
        url = url1
        if k9 == "1":
            url = url2
        if k9 == "0":
            if fenshi1 != "" and fenshi2 != "":
                url =  "https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=30&c=ZhiShuRanking&PhoneOSNew=1&RStart=" + fenshi1 + "&old=1&DeviceID=037520ec-5c84-34a1-8d7a-813a91437308&VerSion=5.13.0.0&IsZZ=0&Token=0&Index=0&REnd=" + fenshi2 + "&apiv=w35&Type="+typeSort+"&IsKZZType=0&UserID=0&PlateID=" + bdm + "&"
            else:
                url = "https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=30&c=ZhiShuRanking&PhoneOSNew=1&old=1&DeviceID=037520ec-5c84-34a1-8d7a-813a91437308&VerSion=5.13.0.0&IsZZ=0&Index=0&apiv=w35&Type="+typeSort+"&IsKZZType=0&PlateID=" + bdm + "&";
        else:
            if fenshi1 != "" and fenshi2 != "":
                url = "https://apphis.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=30&Index=0&c=ZhiShuRanking&PhoneOSNew=1&old=1&DeviceID=00000000-20e2-de83-0000-000075d2bc63&VerSion=5.10.0.2&IsZZ=0&Token=eae05af9b2237485e90e8165e55b0f20&Date="+ rq +"&apiv=w33&Type="+typeSort+"&IsKZZType=0&UserID=1904945&PlateID=" + bdm+ "&RStart=" + fenshi1 + "&REnd=" + fenshi2+ "&";
            else:
                url = "https://apphis.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=30&Index=0&c=ZhiShuRanking&PhoneOSNew=1&old=1&DeviceID=00000000-20e2-de83-0000-000075d2bc63&VerSion=5.10.0.2&IsZZ=0&Token=eae05af9b2237485e90e8165e55b0f20&&Date="+ rq +"&apiv=w33&Type="+typeSort+"&IsKZZType=0&UserID=1904945&PlateID=" + bdm+ "&";

        urls = [url_1025,url]
        responses = concurrent_http_requests(urls)
        datas = {}
        for url, data in responses:
            if url == url_1025:
                datas['url1025'] = data
            if url == url:
                datas['url'] = data


        # 将数据转换为 JSON 并作为响应返回
        self.write(json.dumps(datas))
        self.set_header("Content-Type", "application/json")

class TradedayHandler(tornado.web.RequestHandler):
    def get(self, tt):
        date = datetime.date.fromisoformat(tt)
        one_day = datetime.timedelta(days=1)
        datas = {}
        for i in range(100):
            date_str = date.strftime('%Y-%m-%d')
            xmlHttp3_url3 = "https://apphis.longhuvip.com/w1/api/index.php?Order=1&st=30&a=RealRankingInfo&c=ZhiShuRanking&PhoneOSNew=1&DeviceID=00000000-20e2-de83-0000-000075d2bc63&VerSion=5.12.0.0&Index=0&apiv=w34&Type=1&ZSType=7&Date=" + date_str
            response = requests.get(xmlHttp3_url3)
            data = response.json()
            data_str = json.dumps(data, ensure_ascii=False)
            if "MYSQL数据库链接出错!" in data_str or '"list":[]' in data_str or '参数出错' in data_str:
                date = date - one_day
                continue
            datas['date'] = date_str
            self.write(json.dumps(datas))
            self.set_header("Content-Type", "application/json")
            break


class DatebackHandler(tornado.web.RequestHandler):
    def get(self, dayStr, interval,tt):
        date = datetime.date.fromisoformat(dayStr)
        one_day = datetime.timedelta(days=int(interval))
        datas = {}

        for i in range(100):
            # date 进行一次interval
            date = date + one_day
            date_str = date.strftime('%Y-%m-%d')
            xmlHttp3_url3 = "https://apphis.longhuvip.com/w1/api/index.php?Order=1&st=30&a=RealRankingInfo&c=ZhiShuRanking&PhoneOSNew=1&DeviceID=00000000-20e2-de83-0000-000075d2bc63&VerSion=5.12.0.0&Index=0&apiv=w34&Type=1&ZSType=7&Date=" + date_str
            response = requests.get(xmlHttp3_url3)
            data = response.json()
            data_str = json.dumps(data, ensure_ascii=False)
            if "MYSQL数据库链接出错" not in data_str or '"list":[]' not in data_str or 'errcode":1020' not in data_str:
                datas['date'] = date_str
                self.write(json.dumps(datas))
                self.set_header("Content-Type", "application/json")
                break

# 更新 make_app 函数以包含 DataHandler
def make_app():
    return tornado.web.Application([
        (r"/data/(.*)", DataHandler),
        (r"/writeSource1/(.*)/(.*)/(.*)", WwriteSource1Handler),  # 使用正则表达式捕获参数
        (r"/writeSource2/(.*)/(.*)/(.*)", WwriteSource2Handler),  # 使用正则表达式捕获参数
        (r"/subclass/(.*)", SubclassHandler),  # 使用正则表达式捕获参数
        (r"/update/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)", UpdateHandler),  # 使用正则表达式捕获参数
        (r"/tradeday/(.*)", TradedayHandler),  # 使用正则表达式捕获参数
        (r"/dateback/(.*)/(.*)/(.*)", DatebackHandler),  # 使用正则表达式捕获参数
    ],debug=True, template_path="templates", static_path="static")

if __name__ == "__main__":
    app = make_app()
    app.listen(8889)
    tornado.ioloop.IOLoop.current().start()


